from flask import Blueprint, request
from utilsapp.mysql_con import db_delete, db_insert, db_fetchone, db_update, db_pagelist, db_table_list
from utilsapp.common import parsing_data_id, find_str, assign_value
from utilsapp.utils import get_tomorrow, date_to_str, str_to_date
from datetime import datetime
bluePrint = Blueprint('repair', __name__)
tableName = 'repair'


def plan_list_before():
    res = db_table_list("replan")['data']
    now = datetime.now()
    for item in res:
        if now > item['next_time'] and item['plan_state'] != 2:
            if item['type_id'] == 1:
                # 周期计划 过期 ： count++ ; 生成一条记录；next_time = start_time+间隔 * count
                sql_1 = f"SELECT time from cycle where id ={item['cycle_id']}"
                time = db_fetchone(sql_1)['data']
                start_time = item['start_time']
                next_time = item['next_time']
                count = item['count']
                while now > next_time:
                    next_time = get_tomorrow(
                        date_to_str(start_time), time * count)
                    count = count + 1
                    db_insert("repair",
                              {"device_id": item['device_id'],
                                  "plan_id": item['id'],
                                  "details": "过期自动生成",
                                  "record_state": 2,
                                  "create_time": next_time
                               })
                db_update("replan", {"next_time": date_to_str(next_time),
                                   "count": count}, f"where id =%s", {"mid": item['id']})

            elif item['type_id'] == 2:
                sql = f"SELECT count(id) as num from repair where plan_id = {item['id']}"
                num = db_fetchone(sql)['data']

                if(num ==0) :
                    db_insert("repair", {"plan_id": item['id'],  "details": "过期自动生成",
                          "device_id": item['device_id'], "record_state": 2, "create_time": item['next_time']})
                db_update("replan", {"plan_state": 3},
                          f"where id =%s", {"mid": item['id']})
        if item['type_id'] == 1:
            sql_1 = f"SELECT time from cycle where id ={item['cycle_id']}"
            time = db_fetchone(sql_1)['data']
            next_time = item['next_time']
            start_time = item['start_time']
            count = item['count']
            if next_time < get_tomorrow(date_to_str(start_time), time*count):
                next_time = get_tomorrow(
                    date_to_str(start_time), time * (count+1))
                db_update("replan", {"next_time": date_to_str(
                    next_time)}, f"where id =%s", {"mid": item['id']})


# 分页查询 点巡检记录
@bluePrint.route('/record/getlist', methods=["post", "get"])
def record_list():
    a = request.json
    device_id = assign_value(a, "device_id")
    id = assign_value(a, "id")
    plan_id = assign_value(a, "plan_id")
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    reporter = assign_value(a, "reporter")
    device_name = assign_value(a, "device_name")
    start_time = assign_value(a, "start_time")
    end_time = assign_value(a, "end_time")
    type_id = assign_value(a, "type_id")
    record_state = assign_value(a, "record_state")
    result = assign_value(a, "result")
    # 基础语句
    sql = """SELECT p.id,p.device_id,d.type_id,d.device_name,p.details,p.reporter,p.create_time,dt.name as 
    device_type,p.record_state,p.result,p.photo,p.plan_id,pl.title from repair p LEFT JOIN device d on d.id = p.device_id left join 
    device_type dt on d.type_id = dt.id left join replan pl on p.plan_id = pl.id"""
    # 条件语句
    query = ' where 1=1 '
    if scoped != '':
        query += f" and d.{scoped}"
    if id != '':
        query += f" and p.id = {id} "
    if plan_id != '':
        query += f" and p.plan_id = {plan_id} "
    if reporter != '':
        query += f" and p.reporter like '%{reporter}%' "
    if device_name != '':
        query += f" and d.device_name like '%{device_name}%' "
    if type_id != '':
        query += f" and d.type_id = {type_id}"
    if record_state != '':
        query += f" and p.record_state = {record_state}"
    if result != '':
        query += f" and p.result = {result}"
    if start_time != '':
        query += f" and p.create_time >'{start_time}'"
    if end_time != '':
        query += f" and p.create_time <'{end_time}' "
    if device_id != '':
        query += f" and p.device_id = {device_id}"
    sql_1 = f"select count(id) as num from ({sql} {query} and p.record_state = 1) as a"
    sql_2 = f"select count(id) as num from ({sql} {query} and p.record_state = 2) as a"
    sql = sql + query + " ORDER BY p.create_time desc"
    res = db_pagelist(sql, request.json["page"], request.json['size'])

    num1 = db_fetchone(sql_1)
    num2 = db_fetchone(sql_2)

    res['stat'] = {
        "checked": num1['data'],
        "unchecked": num2['data'],
    }
    return res


# 巡检记录 删除
@bluePrint.route('/record/delete', methods=["post"])
def record_delete():
    id = request.json['id']
    return db_delete('repair', f'WHERE id=%s', {'id': id})


@bluePrint.route('/cycle/list')
def cycle_list():
    return db_table_list('cycle')


# 新增
@bluePrint.route('/record/add', methods=["post"])
def record_add():
    # 生成巡检记录，计划执行次数 ++
    res = db_insert(tableName, request.json)

    plan_id = request.json['plan_id']
    sql_1 = f"SELECT count from replan where id ={plan_id}"
    count = db_fetchone(sql_1)['data']

    if count == "":
        count = 0
    db_update("replan", {"count": count+1}, f"where id =%s", {"mid": plan_id})
    return res


@bluePrint.route('/record/edit', methods=['post'])
def record_set():
    id = request.json['id']
    keys_not_add = ['id','device_name','device_type','title','type_id']
    addModel = {key: request.json[key]
                for key in request.json if key not in keys_not_add}
    return db_update("repair", addModel, f"WHERE id = %s", {"id": id})


# 分页查询 点巡检 计划 方案
@bluePrint.route('/replan/getlist', methods=["post"])
def plan_list(id=''):
    plan_list_before()
    a = request.json
    id = assign_value(a, "id")
    type_id = assign_value(a, "type_id")
    scope_id = assign_value(a, "scope_id", 0)
    scoped = parsing_data_id(scope_id, request)
    device_name = assign_value(a, "device_name")
    cycle_type = assign_value(a, "device_name")
    cycle_id = assign_value(a, "cycle_id")
    plan_state = assign_value(a, "plan_state")
    content_id = assign_value(a, "content_id")
    # 基础语句
    sql = """SELECT p.id,p.title,p.content,p.plan_state,d.id as device_id,d.device_name,dt.id as device_type_id,dt.name as device_type,p.type_id,
    p.count,p.start_time,p.next_time,c.id as cycle_id,c.name as cycle from replan p LEFT JOIN device d on p.device_id = d.id LEFT JOIN device_type dt
    on dt.id = d.type_id left JOIN cycle c on p.cycle_id = c.id """
    # 条件语句
    query = ' where 1=1 '
    if scoped != '':
        query += f" and d.{scoped}"
    if id != '':
        query += f" and p.id = {id}"
    if device_name != '':
        query += f" and d.device_name like '%{device_name}%'"
    if type_id != '':
        query += f" and p.type_id = {type_id}"
    if cycle_id != '':
        query += f" and p.cycle_id = {cycle_id}"
    if cycle_type != '':
        query += f" and p.type_id = {cycle_type}"
    if plan_state != '':
        query += f" and p.plan_state = {plan_state}"
    if content_id!='':
        query += f" and p.content_id = {content_id} "
    sql_1 = f"select count(id) as num from ({sql} {query} and p.plan_state=1) as a"
    sql_2 = f"select count(id) as num from ({sql} {query} and p.plan_state=2) as a"
    sql_3 = f"select count(id) as num from ({sql} {query} and p.plan_state=3) as a"
    sql = sql+query + " ORDER BY p.next_time desc"
    res = db_pagelist(sql, request.json["page"], request.json['size'])
    num1 = db_fetchone(sql_1)
    num2 = db_fetchone(sql_2)
    num3 = db_fetchone(sql_3)
    res['stat'] = {
        "running": num1['data'],
        "failed": num2['data'],
        "pastdue": num3['data']
    }
    return res


@bluePrint.route('/replan/edit', methods=['post'])
def plan_set():
    id = request.json['id']
    type_id = request.json['type_id']
    if type_id == 1:
        cycle_id = request.json['cycle_id'] if request.json['cycle_id'] else 0
        if cycle_id != 0:
            sql_1 = f"SELECT time from cycle where id ={cycle_id}"
            time = db_fetchone(sql_1)['data']
            next_time = get_tomorrow(request.json['start_time'], time)
            request.json['next_time'] = next_time
    keys_not_add = ['id', 'type_id']
    addModel = {key: request.json[key]
                for key in request.json if key not in keys_not_add}
    return db_update("replan", addModel, f"WHERE id = %s", {"id": id})


# 新增计划
@bluePrint.route('/replan/add', methods=["post"])
def plan_add():

    type_id = request.json['type_id']
    if type_id == 1:  # 如果是周期计划
        cycle_id = request.json['cycle_id'] if request.json['cycle_id'] else 0
        if cycle_id != 0:
            sql_1 = f"SELECT time from cycle where id ={cycle_id}"
            time = db_fetchone(sql_1)['data']
            next_time = get_tomorrow(request.json['start_time'], time)
            request.json['next_time'] = next_time
    return db_insert('replan', request.json)


# 删除
@bluePrint.route('/replan/delete', methods=["post"])
def plan_delete():
    id = request.json['id']
    return db_delete('replan', f'WHERE id=%s', {'id': id})


# 停止 or 启动计划
@bluePrint.route('/replan/stop', methods=["post"])
def plan_stop():
    id = request.json['id']
    types = request.json['types']
    request.json['plan_state'] = 1 if request.json['plan_state'] == 2 else 2
    keys_not_add = ['id']
    addModel = {key: request.json[key]
                for key in request.json if key not in keys_not_add}
    return db_update("replan", addModel, f"WHERE id = %s", {"id": id})
